import SQLiteParser
from physical import *

chats = list()
user_name_id_map = dict()
chat = Chat()
chat.Id.Value = 'QuizKampen chat'

for fs in ds.FileSystems:
	for f in fs.Search('se.feomedia.quizkampen/databases/quizkampen'):
		if f.AbsolutePath.endswith('quizkampen'):
			db = SQLiteParser.Database.FromNode(node)
			for record in db.ReadTableRecords(table_name):
				to_from_pair = set()
				to_from_pair.add(record['to_id'].Value)
				to_from_pair.add(record['from_id'].Value)
				if to_from_pair not in chats:
					chats.append(to_from_pair)

				for record in db.ReadTableRecords('qk_games'):
					user_name_id_map[str(record['opponent_id'].Value)]=record['opponent_name'].Value
					
				for record in db.ReadTableRecords('qk_users'):
					user_name_id_map[str(record['id'].Value)]=record['name'].Value

				for chat_pairs in chats:
					participant1 = chat_pairs.pop()
					participant2 = chat_pairs.pop()
					for record in db.ReadTableRecords(table_name):
						im = InstantMessage()
						test1 = record['to_id'].Value == participant1 and record['from_id'].Value == participant2
						test2 = record['to_id'].Value == participant2 and record['from_id'].Value == participant1
						if test1 or test2:
							fromParty = Party.MakeFrom(record['from_id'].Value,None)
							if user_name_id_map.has_key(str(record['from_id'])):
								fromParty.Name.Value = user_name_id_map[str(record['from_id'])]
							toParty = Party.MakeTo(record['to_id'].Value,None)
							if user_name_id_map.has_key(str(record['to_id'])):
								toParty.Name.Value = user_name_id_map[str(record['to_id'])]
							im.From.Value = fromParty
							im.To.Add(toParty)
							im.Body.Value = record['text']
							im.TimeStamp.Value = TimeStamp.FromFileTime(time.strptime(record['datetime']).ToFileTime())
							chat.Messages.Add(im)
ds.models.add(chat)